<template>
  <div class="l-rblock">
    <el-input
      ref="main"
      :placeholder="$t(placeholder)"
      v-model="selectValue"
      :size="size"
      :clearable="disabled ? false : clearable"
      :disabled="disabled"
      @focus="handleShow"

      @clear="handleClear"
    >
      <span slot="append" @click="handleShow">
        <el-button slot="append" icon="learun-icon-form"></el-button>
      </span>
    </el-input>
    <l-dbsource-selectdialog
      :visible.sync="dialogVisible"
      :multiple="false"
      @select="dbsourceSelect"
    >
    </l-dbsource-selectdialog>
  </div>
</template>
<script>
const api = window.$api.data.dbsource;
export default {
  name: "l-dbsource-select",
  props: {
    value: {},
    size: {
      type: String,
      default: "mini",
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      dialogVisible: false,
      selectData: null,
    };
  },
  computed: {
    selectValue: {
      get() {
        if (this.selectData) {
          return this.selectData.f_Name;
        }
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
  watch: {
    value: {
      handler(val) {
        if (this.selectData == null || this.selectData.f_Code != val) {
          this.loadData(val);
        }
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    async loadData(code) {
      if (code) {
        const data = await this.$awaitWraper(api.get(code));
        if (data && data.f_Code == this.value) {
          this.selectData = data;
        }
      }
      else{
        this.selectData = null 
      }
      this.$emit("init", this.selectData);
    },
    handleChange(val) {
      this.$emit("change", val);
    },
    handleClear(){
      this.$emit("change", undefined);
    },
    handleShow() {
      this.dialogVisible = true;
    },
    async dbsourceSelect(list) {
      console.log(list,'list');
      const { f_Code, f_Name, f_Type,f_Sql } = list[0];
      const data = { f_Code, f_Name, f_Type,f_Sql };
      this.selectData = data;
      this.selectValue = f_Code;
      this.handleChange(data);
    },
  },
};
</script>